package com.example.transdemo.controller;

/*
 * @author zzr
 * @date: 2025/10/03  21:12
 * @description:
 */

import com.example.transdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RequestMapping("/user2")
@RestController
public class UserController2 {

    @Autowired
    private UserService userService;
    // 事务管理器
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    // 事务属性
    @Autowired
    private TransactionDefinition transactionDefinition;


    @RequestMapping("/registry2")
    public String registry(String name, String password) {

        // 开启事务
        TransactionStatus  transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        // 用户注册
        userService.registryUser(name, password);

        // 提交事务
        dataSourceTransactionManager.commit(transactionStatus);

        // 回滚事务
//        dataSourceTransactionManager.rollback(transactionStatus);
        return "注册成功";
    }
}
